<?php

/*
 * 依设定日期跟新门店和公司
 */

$serverFilePath = realpath(dirname(__FILE__));;//realpath(dirname(__FILE__)); //$_SERVER["SCRIPT_FILENAME"];
$doc_dir = strrpos($serverFilePath, '/crontab');
$doc_dir = substr($serverFilePath, 0, $doc_dir + 1);   //project root
include_once $doc_dir . '/config/lib/Config.php';
include_once $doc_dir . '/plugin/Logging.php';

set_time_limit(0);
error_reporting(E_ALL);
header("Content-type:text/html;charset:utf-8");

$config_ini = $doc_dir . 'config/config.ini';

$ini_array = parse_ini_file($config_ini, true);
$db_array = $ini_array['DB'];
$getWebsite = $ini_array['WebSite'];
$con = mysqli_init();

mysqli_real_connect($con, $db_array['host'], $db_array['id'], $db_array['pwd'], $db_array['database'], $db_array['port']);
mysqli_set_charset($con, $db_array['encoding']);


$base = array(
    'url' => "http://storemap.ganso.com.cn/service/nusoapServerWSDL.php?wsdl",
);

$options = array(
    'soap_version' => SOAP_1_1,
    'exceptions' => true,
    'trace' => 1,
    'cache_wsdl' => WSDL_CACHE_NONE
);

$client = new SoapClient($base['url'], $options);
$storelist = array();

try {
    $response = $client->__soapCall('Store.getStores', array('province' => '', 'query' => '', 'status' => '2,4,5'));
    $response = json_decode(json_encode((array) simplexml_load_string($response)), 1);
    $storelist = $response['stores']['store'];

} catch (Exception $e) {
    var_dump($e);
}
try {
    $response = $client->__soapCall('Store.getCompanies', array());
    $response = json_decode(json_encode((array) simplexml_load_string($response)), 1);

    $comlist = $response['companies']['company'];
} catch (Exception $e) {
    var_dump($e);
}

$sql = "UPDATE xd_store SET status=3 ,business_status=3  ";
$result = mysqli_query($con, $sql);
foreach ($storelist as $k => $val) {
    $field = array();
    $store_id = $field['store_id'] = $val['storeCode']; //门店号码
    $field['company_id'] = empty($val['companyCode']) ? '' : $val['companyCode']; //公司号码
    $field['department_id'] = empty($val['departmentCode']) ? '' : $val['departmentCode']; //销售部门id
    $field['storename'] = empty($val['storeName']) ? '' : $val['storeName']; //门店名称
    $field['tel'] = empty($val['tel']) ? '' : $val['tel'];
    $field['front_province'] = empty($val['province']) ? '' : $val['province'];
    $field['front_city'] = empty($val['city']) ? '' : $val['city'];
    $field['front_area'] = empty($val['area']) ? '' : $val['area'];
    $field['front_address'] = $val['address'];
    $field['province'] = empty($val['provinceCode']) ? '' : $val['provinceCode'];
    $field['city'] = empty($val['cityCode']) ? '' : $val['cityCode'];
    $field['area'] = empty($val['areaCode']) ? '' : $val['areaCode'];
    $field['address'] = $val['address'];

    $field['longitude'] = empty($val['longitude']) ? '' : $val['longitude']; //经度
    $field['latitude'] = empty($val['latitude']) ? '' : $val['latitude']; //纬度
    $field['type'] = empty($val['type']) ? '' : $val['type']; //营业项目
    $field['terminal_id'] = empty($val['mmtTerminal']) ? '' : $val['mmtTerminal']; //终端号
    $field['systatus'] = empty($val['mmtStatus']) ? '' : $val['mmtStatus']; //系统状态
    $field['user_authority'] = empty($val['mmtMemberLoginAuth']) ? '' : $val['mmtMemberLoginAuth']; //会员登录权限
    $field['business_status'] = empty($val['status']) ? '' : $val['status']; //营业状态
    $field['status'] = $field['business_status'];
    $field['property'] = empty($val['property']) ? '' : (int)$val['property']; //门店属性
    $field['opendt'] = empty($val['openDate']) ? 'null' : $val['openDate'];
    $field['closedt'] = empty($val['closeDate']) ? '0000-00-00 00:00:00' : $val['closeDate'][0];   # Mysql 5.7 如果接收未空 传入 0000-00-00 00:00:00

    # 新增必填字段 Mysql5.7 低版本略过
    $field['stype'] = 0;
    $field['delivery'] = 'N';
    $field['editor'] = 0;

    $field=mysql_escape($field);

    $sql = "SELECT storename FROM xd_store WHERE  store_id = {$store_id}";
    $result = mysqli_query($con, $sql);

    if (!empty($result) && count($result) > 0) {
        $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
    }

    //if ($field['company_id']==1001 || $store_id==100816  || $store_id==100932  || $store_id==100936 ) {
        if (empty($row)) {
            $pwd = '123456';
            $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
            $l = strlen($str) - 1;
            $salt = '';
            for ($index = 0; $index <= 20; $index++) {
                $salt .= $str[rand(0, $l)];
            }
            $field['salt'] = $salt;
            $saltpwd = sha1($salt . $pwd);
            $field['password'] = $saltpwd;
            $field['isdeleted'] = 1;

            $values = insertValue($field);
            $sql = "insert into xd_store {$values}";

//        echo '<pre>';
//        var_dump($field);die;
//        echo $sql."\n";exit;
            $result = mysqli_query($con, $sql);
            echo (date('Y-m-d H:i:s') . " 新增门店：" . $field['store_id'] . $field['storename']) . ', result:' . $result . "\n";

        } else {
            $field['isdeleted'] = 0;
            unset($field['storename']);
            $values = updateValue($field);
            $sql = "update xd_store set {$values}  WHERE store_id = {$store_id}";

            $result = mysqli_query($con, $sql);
            if (!$result) {
                echo ("门店更新失败：" . $field['store_id'] . $field['storename']) . "\n";
            }
        }
   // }


}


foreach ($comlist as $k => $val) {
    $info = array();
    $code = $info['code'] = $val['companyCode'];
    $info['name'] = $val['companyName'];
    $info['is_parent'] = 1;
    $info['parent_code'] = 0;
    # 新增必填字段 Mysql5.7 低版本略过
    $info['editor'] = 0;

    $sql = "SELECT code FROM xd_company WHERE isdeleted = 0 and code = {$code} and is_parent = 1";
    $result = mysqli_query($con, $sql);
    //var_dump($result);
    if (!empty($result) && count($result) > 0) {
        $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
    }
    if (empty($row)) {
        # 新增分司密码 初始未123
        $pwd='123456';
        $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
        $l = strlen($str)-1;
        $salt = '';
        for ($index = 0; $index <= 20; $index++) {
            $salt .= $str[rand(0, $l)];
        }
        $info['salt'] = $salt;
        $saltpwd = sha1($salt . $pwd);
        $info['password'] = $saltpwd;
        $values = insertValue($info);
        $sql = "insert into xd_company {$values}";
//         echo $sql."\n";exit;
        $id = mysqli_query($con, $sql);
        echo ("新增公司：" . $info['code'] . $info['name']) . "\n";

    } else {
        $values = updateValue($info);
        $sql = "update xd_company set {$values}  WHERE code = {$code} and is_parent = 1";
        //echo $sql."\n";
        $result = mysqli_query($con, $sql);
        if (!$result) {
            echo ("公司更新失败：" . $info['code'] . $info['name']) . "\n";
        }
    }
    // var_dump($val['departments']['department']);exit;
    //销售部门
    if (!empty($val['departments']) && isset($val['departments']['department']) && count($val['departments']['department']) > 0) {
        foreach ($val['departments']['department'] as $key => $value) {
            $info = array();
            if (is_array($value)) {
                //var_dump($value);
                //$info = array();
                $code = $info['code'] = $value['departmentCode'];
                $info['name'] = $value['departmentName'];
                $info['is_parent'] = 0;
                $info['parent_code'] = $val['companyCode'];
            } else {
                $code = $info['code'] = $val['departments']['department']['departmentCode'];
                $info['name'] = $val['departments']['department']['departmentName'];
                $info['is_parent'] = 0;
                $info['parent_code'] = $val['companyCode'];
                //var_dump($info);
                //die;
            }

            if($code == $val['companyCode']){
                continue;
            }
            $sql = "SELECT code FROM xd_company WHERE isdeleted = 0 and code = {$code} and is_parent = 0";
            $result = mysqli_query($con, $sql);
            //var_dump($result);
            if (!empty($result) && count($result) > 0) {
                $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
            }
            if (empty($row)) {
                $values = insertValue($info);
                $sql = "insert into xd_company {$values}";
                //echo $sql."\n";
                $result = mysqli_query($con, $sql);
                echo ("新增销售部门：" . $info['code'] . $info['name']) . "\n";
            } else {
                $values = updateValue($info);
                $sql = "update xd_company set {$values}  WHERE code = {$code} and is_parent = 0";
                //echo $sql."\n";
                $result = mysqli_query($con, $sql);
                if (!$result) {
                    echo ("销售部门更新失败：" . $info['code'] . $info['name']) . "\n";
                }
            }
        }
    }
}

echo ('....................................');

function insertValue($arr) {
    $keys = array();
    $values = array();

    foreach ($arr as $k => $val) {
        $keys[] = "`" . $k . "`";
        $values[] = "'" . $val . "'";
    }
    $ks = implode(",", $keys);
    $vals = implode(",", $values);
    $re = "(" . $ks . ", createdt) values (" . $vals . ", now())";

    return $re;
}

function updateValue($arr) {
    $result = array();
    foreach ($arr as $k => $val) {
        $result[] = "`" . $k . "`" . "='" . $val . "'";
    }
    $result[] = "`updatedt`" . "=now() ";

    $re = implode(",", $result);
    return $re;
}

function mysql_escape($content) {
    if (!get_magic_quotes_gpc()) {

        if (is_array($content)) {
            foreach ($content as $key => $value) {
                $content[$key] = addslashes($value);
            }
        } else {
            $content = addslashes($content);
        }
    }
    return $content;
}
?>

